import { addApi, getApis, removeApi, updateApi } from '@/services/ant-design-pro/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Button, message, Popover } from 'antd';
import React, { useRef, useState } from 'react';
import EditForm from './componets/EditForm';

/**
 * @en-US Add menu
 * @zh-CN 添加菜单
 * @param fields
 */
const handleAdd = async (fields: API.ApiItem) => {
  const hide = message.loading('正在添加');
  try {
    await addApi({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

/**
 * @en-US Update api
 * @zh-CN 更新API
 * @param fields
 */
const handleUpdate = async (fields: API.ApiItem) => {
  const hide = message.loading('正在更新');
  try {
    await updateApi({ ...fields });
    hide();
    message.success('Updated successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Updating failed, please try again!');
    return false;
  }
};

/**
 * @en-US Delete api
 * @zh-CN 删除API
 * @returns
 */
const handleDelete = async (fields: API.RoleItem) => {
  const hide = message.loading('正在删除');
  try {
    await removeApi({ ...fields });
    hide();
    message.success('Deleted successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Deleting failed, please try again!');
    return false;
  }
};

const ApiList: React.FC = () => {
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const actionRef = useRef<ActionType>();

  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  /**
   * @en-US Pop-up window of edit window
   * @zh-CN 编辑窗口的弹窗
   *  */
  const [setModalOpen, handleSetModalOpen] = useState<boolean>(false);

  const [currentRow, setCurrentRow] = useState<API.ApiItem>();

  const columns: ProColumns<API.ApiItem>[] = [
    { title: 'ID', dataIndex: 'id', fixed: 'left', valueType: 'digit', hideInSearch: true },
    { title: 'API路径', dataIndex: 'path', fixed: 'left' },
    { title: '说明', dataIndex: 'description', fixed: 'left' },
    { title: '分组', dataIndex: 'apigroup', fixed: 'left' },
    {
      title: '方法',
      dataIndex: 'method',
      fixed: 'left',
      valueType: 'select',
      request: async () => [
        { label: '', value: undefined },
        { label: 'GET', value: 'GET' },
        { label: 'POST', value: 'POST' },
        { label: 'PUT', value: 'PUT' },
        { label: 'DELETE', value: 'DELETE' },
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="set"
          onClick={() => {
            setCurrentRow(record);
            handleSetModalOpen(true);
          }}
          type="primary"
        >
          设置
        </Button>,
        <Popover
          key="delete"
          content={
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <p style={{ marginBottom: 8 }}>您确定要删除这个API吗？</p>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Button
                  type="primary"
                  danger
                  style={{ marginRight: 8 }}
                  onClick={async () => {
                    const success = await handleDelete(record);
                    if (success) {
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    }
                  }}
                >
                  确认
                </Button>
                <Button style={{ marginLeft: 8 }}>取消</Button>
              </div>
            </div>
          }
        >
          <Button type="primary" danger>
            删除
          </Button>
        </Popover>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.ApiItem, API.PageParams>
        headerTitle=" 查询API"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 添加API
          </Button>,
        ]}
        request={getApis}
        columns={columns}
      />
      <EditForm
        title="添加API"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />
      <EditForm
        title="编辑API"
        open={setModalOpen}
        onOpenChange={handleSetModalOpen}
        onFinish={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleSetModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        values={currentRow}
      />
    </PageContainer>
  );
};

export default ApiList;
